﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TimKen.DataEntity;
using TimKen.BussLogic;
using TimKen.App;
using System.Data;
using System.Text;
using Microsoft.ApplicationBlocks.Data;
using System.IO;
using Common;


namespace TimKen.Web.Admin.Order
{
    public partial class Order_Info : TimKen.App.AdminPage
    {


        public DataEntity.Order Order = new TimKen.DataEntity.Order();
        protected OrderManager OrderManager = new OrderManager();
        public override string ActionCode
        {
            get
            {

                return "86";
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindResources();
                if (Request.QueryString["OrderID"] != null)
                {
                    OrderID = Request.QueryString["OrderID"];
                }
                BindTransType();
            }
            BindData();
        }


        public string OrderID
        {
            get
            {
                if (ViewState["OrderID"] != null)
                    return ViewState["OrderID"].ToString();
                else
                    return "";
            }
            set
            {
                ViewState["OrderID"] = value;
            }
        }


        private void BindData()
        {
            Order = OrderManager.GetModel(OrderID, LanguageID);
            ///绑定预计交货日期和运费
            if (Order.PlanDate.HasValue)
                this.txtPlanDate.Text = Order.PlanDate.Value.ToShortDateString();
            if (Order.Freight.HasValue)
                this.txtFreight.Text = Order.Freight.Value.ToString();

            TimKen.BussLogic.OrderItemManager orderItemM = new TimKen.BussLogic.OrderItemManager();
            DataSet orderItems = orderItemM.GetOrderItems(OrderID);
            repOrderItems.DataSource = orderItems;
            repOrderItems.DataBind();


            this.fckContent.Value = Order.ContractTerm;
            if (Order.OrderStatus == OrderStatus.CustomerConfirmed || Order.OrderStatus == OrderStatus.ForFirstBridgeSOFreightConfirm)
            {
                this.btnSave.Enabled = true;
            }

            //绑定运输类型
            if (Order.ShipType.HasValue)
                for (int i = 0; i < ddlTransType.Items.Count; i++)
                {
                    if (ddlTransType.Items[i].Value == Order.ShipType.Value.ToString())
                        ddlTransType.Items[i].Selected = true;
                }

            ///如果

            //如果运输方式自提,则不允许修改运输类型,运费,预计交货日期
            //if (Order.ShipType.HasValue)
            //    if (Order.ShipType.Value == 1)
            //    {
            //        this.ddlTransType.Enabled = false;
            //        this.txtFreight.Enabled = false;
            //        this.txtPlanDate.Enabled = false;
            //    }

            //如果订单状态已经不是等待EC确认,则不允许再进行修改
            if (Order.OrderStatus != OrderStatus.ForFirstBridgeSOFreightConfirm)
            {
                this.ddlTransType.Enabled = false;
                this.txtFreight.Enabled = false;
                this.txtPlanDate.Enabled = false;
                this.btnCancel.Enabled = false;
                this.btnConfirm.Enabled = false;
            }

            if (Order.OrderStatus == OrderStatus.CustomerConfirmed)
                this.btnCancel.Enabled = true;

            if (Order.OrderStatus != OrderStatus.ConfirmPayment)
                this.btnConfirmPayment.Enabled = false;

            //如果订单的合同状态没有状态,并且订单状态为等待b1审核.则可以确认合同
            if (Order.ContractStatus == 0 && Order.OrderStatus == OrderStatus.ForB1Check)
                this.btnConfirmContract.Enabled = true;
        }

        protected void BindResources()
        {
            btnCancel.Text = GetLangString("CancelOrder");
            btnConfirm.Text = GetLangString("ConfirmOrder");
            btnConfirmContract.Text = GetLangString("ConfirmContract");
            btnConfirmPayment.Text = GetLangString("ConfirmPayment");
        }
        protected void BindTransType()
        {
            TimKen.BussLogic.TransTypeManager ttM = new TimKen.BussLogic.TransTypeManager();
            DataSet transDS = ttM.GetList(LanguageWhereStr);
            ddlTransType.DataSource = transDS;
            ddlTransType.DataBind();
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            SaveOrder();

            Order = OrderManager.GetModel(OrderID);

            Order.ShipType = Convert.ToInt32(this.ddlTransType.SelectedValue);

            //如果运输方式非自提,则判断运费和运输方式
            if (txtPlanDate.Text == "")
            {
                Alert(GetLangString("ExpectDateNeeded"));
                return;
            }
            else
            {
                DateTime expectDate;
                if (DateTime.TryParse(txtPlanDate.Text, out expectDate))
                {
                    Order.PlanDate = expectDate;
                }
                else
                {
                    Alert(GetLangString("ErrorExpectDate"));
                    return;
                }
            }
            try
            {
                Order.PlanDate = Convert.ToDateTime(this.txtPlanDate.Text.Trim());
            }
            catch
            {
                Alert(GetLangString("ErrorDate"));
                return;
            }
            if (txtFreight.Text == "")
            {
                Alert(GetLangString("FreightNeeded"));
                return;
            }
            else
            {
                decimal freight;
                if (Decimal.TryParse(txtFreight.Text, out freight))
                {
                    Order.Freight = freight;
                }
                else
                {
                    Alert(GetLangString("ErrorFreight"));
                    return;
                }
            }
            Order.OrderStatus = OrderStatus.CustomerConfirmed;
            this.OrderManager.Update(Order);


            Tools.SendOrderConfirmdEmail(Order.OrderID);
            Response.Redirect(Request.RawUrl);
        }
        protected void btnConfirmPayment_Click(object sender, EventArgs e)
        {
            Order = OrderManager.GetModel(OrderID);

            //设置状态为审核通过
            Order.OrderStatus = OrderStatus.ForB1Check;

            OrderManager.Update(Order);
            Response.Redirect(Request.RawUrl);
        }

        //EC管理员直接取消订单
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Order = OrderManager.GetModel(OrderID);
            OrderItemManager oim = new OrderItemManager();
            DataSet ds = oim.GetOrderItems(Order.OrderID);
            //释放物料的锁库存量
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                int productID = int.Parse(dr["ProductID"].ToString());
                decimal quantity = int.Parse(dr["Quantity"].ToString());

                ProductManager pm = new ProductManager();
                DataEntity.Product product = pm.GetModel(productID);

                if (product.BookedQty >= quantity)
                    product.BookedQty = product.BookedQty - quantity;

                pm.Update(product);
            }

            //更新订单状态
            Order.OrderStatus = OrderStatus.Cancel;
            OrderManager.Update(Order);

            //更新客户的EC额度
            CustomerManager ctmM = new CustomerManager();
            TimKen.DataEntity.Customer customer = ctmM.GetModel(Order.CustomerID);
            customer.ECOrdersBalance = customer.ECOrdersBalance - Order.TotalAmount;
            ctmM.Update(customer);


            Response.Redirect(Request.RawUrl);
        }
        //确认合同
        protected void btnConfirmContract_Click(object sender, EventArgs e)
        {
            //更新合同状态
            Order = OrderManager.GetModel(OrderID);
            Order.ContractStatus = 1;
            OrderManager.Update(Order);

            Response.Redirect(Request.RawUrl);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveOrder();
            BindData();
        }

        public void SaveOrder()
        {
            Order = OrderManager.GetModel(OrderID);
            Order.ContractTerm = this.fckContent.Value;


            Order.BaseAmount = 0;
            Order.TotalAmount = 0;
            Order.TaxAmount = 0;
            foreach (RepeaterItem item in this.repOrderItems.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {

                    string ItemID = (item.FindControl("hfItemID") as HiddenField).Value;
                    TextBox txtBaseAmount = item.FindControl("txtBaseAmount") as TextBox;
                    TextBox txtRequestDate = item.FindControl("txtRequestDate") as TextBox;

                    BussLogic.OrderItemManager oim = new OrderItemManager();
                    DataEntity.OrderItem orderitem = oim.GetModel(ItemID);

                    orderitem.RequestDate = Convert.ToDateTime(txtRequestDate.Text);
                    orderitem.BaseAmount = Convert.ToDecimal(txtBaseAmount.Text);

                    orderitem.TaxAmount = orderitem.BaseAmount * orderitem.TaxRate;
                    orderitem.TotalAmount = orderitem.BaseAmount + orderitem.TaxAmount;

                    Order.BaseAmount += orderitem.BaseAmount;
                    Order.TotalAmount += orderitem.TotalAmount;
                    Order.TaxAmount += orderitem.TaxAmount;

                    oim.Update(orderitem);
                }
            }

            OrderManager.Update(Order);



        }

        protected void repOrderItems_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Order = OrderManager.GetModel(OrderID);

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                TextBox txtBaseAmount = e.Item.FindControl("txtBaseAmount") as TextBox;
                TextBox txtRequestDate = e.Item.FindControl("txtRequestDate") as TextBox;

                if (Order.OrderStatus == OrderStatus.CustomerConfirmed || Order.OrderStatus == OrderStatus.ForFirstBridgeSOFreightConfirm)
                {
                    txtBaseAmount.Enabled = true;
                    txtRequestDate.Enabled = true;
                }

                else
                {
                    txtRequestDate.Enabled = false;
                    txtBaseAmount.Enabled = false;

                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            BindData();
            //Response.Write(Request.RawUrl);
            GetExport();
        }
        /// <summary>
        /// 导出方法
        /// </summary>
        /// <param name="gridview"></param>
        private void GetExport()
        {
            //Response.Clear();
            //Response.Buffer = true;
            //Response.Charset = "GB2312";
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); ;
            //Response.AddHeader("content-disposition", "attachment; filename=MyFiles.xls");
            //Response.ContentType = "application/excel";
            //Page.EnableViewState = false;
            //foreach (RepeaterItem te in rpt.Items)
            //{
            //    HiddenField fd = te.FindControl("hfItemID") as HiddenField;
            //    fd.Visible = false;
            //    TextBox TX = te.FindControl("txtRequestDate") as TextBox;
            //    TX.Visible = false;
            //    TextBox TX1 = te.FindControl("txtBaseAmount") as TextBox;
            //    TX1.Visible = false;
            //}
            //StringWriter sw = new StringWriter();
            //HtmlTextWriter htw = new HtmlTextWriter(sw);
            //table.RenderControl(htw);
            //Response.Write(sw.ToString());
            //Response.End();
        }
        /// <summary>
        /// 导出订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> dtDictText = new Dictionary<string, string>();
            dtDictText.Add("CardCode", "客户编号");
            dtDictText.Add("CardName", "客户名称");
            dtDictText.Add("DocDate", "订单生成日期");
            dtDictText.Add("ECOrderNum", "EC订单编号");
            dtDictText.Add("ECLineNum", "EC订单行号");
            dtDictText.Add("ItemCode", "产品编号（物料号)");
            dtDictText.Add("Quantity", "订购数量");
            dtDictText.Add("Prcie", "单价");
            dtDictText.Add("LineTotal", "行总价");
            dtDictText.Add("RequestDate", "需求日期");
            if (!string.IsNullOrEmpty(Order.Creator) && !string.IsNullOrEmpty(Order.OrderNo))
            {
                DataTable dt = OrderManager.GetOrderDetail(Order.Creator, Order.OrderNo).Tables[0];
                DataRow dataRow = dt.NewRow();

                //int count = 0;
                //foreach (KeyValuePair<string, string> item in dtDictText)
                //{
                //    dataRow[count] = item.Key;
                //    count++;
                //}
                //dt.Rows.InsertAt(dataRow, 0);
             
                try
                {
                    MyNPOIHelper.ExportByWeb(dtDictText, "Export Order", "OrderItem" + Order.OrderNo, HttpContext.Current, dt);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }

            }
        }
        /// <summary>
        /// 导入拆分订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void bImportExcel_Click(object sender, EventArgs e)
        {
            if (Path.GetExtension(this.fileExcel.FileName) == ".xls")
            {
                this.fileExcel.SaveAs(Server.MapPath("~/Admin/Files/" + this.fileExcel.FileName.Replace(" ", "_")));
                try
                {
                    DataTable dt = MyNPOIHelper.Import(Server.MapPath("~/Admin/Files/" + this.fileExcel.FileName.Replace(" ", "_")));
                    //验证数据

                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
            }
            else
            {
                Alert("请确定您上传的文件为Office2003格式(.xls)");
            }
        }
    }
}
